<?php
/**
 * 统计每日会员的盈利情况，记录数据库，方便以后做报表查询3
 */
defined('IN_YuLin') || exit('NO PERMIT!');
// 获取昨天所有订单， 并按用户计算支出与营收数据， 存入数据库。
echo '<pre>';
// 昨天凌晨的时间点
$btime   = strtotime( date('Y-m-d', strtotime('-1 day')) );
// 统计数据记录表
$profitTab = Table('user_lottery_profit');
// 检查昨天的数据有没有统计到数据库
$checkSql  = 'SELECT count(id) as cnt FROM ' . $profitTab . ' WHERE datetime = ' . $btime;
$checkFlag = $db->getrow($checkSql);
if ($checkFlag['cnt'] > 0) exit('已统计昨天数据！');

// 今天凌晨的时间点
$etime   = strtotime( date('Y-m-d') );
$mainTab = Table('lottery_order_main');
$where   = ' WHERE createtime >= ' . $btime . ' AND createtime < ' . $etime;
$sql     = 'SELECT id, uid, amount, prize, platform FROM ' . $mainTab . $where;
$todayOrderList = $db->getall($sql);

// 直接按用户计算盈利数据
$profitData = array();
foreach ($todayOrderList as $k => $v){
    $profitData[$v['uid']]['bet_amount']    += $v['amount'];
    $profitData[$v['uid']]['prize_amount']  += $v['prize'];
    $profitData[$v['uid']]['winner_amount'] += $v['prize'] - $v['amount'];
}
// 准备写入数据库保存
foreach ($profitData as $pk => $pv){
    $pv['uid']      = $pk;
    $pv['datetime'] = $btime;
    $insSql = 'INSERT INTO ' . $profitTab . ' SET ' . CreateUpdateSql($pv);
    $db->exec($insSql);
}
echo 'end';

